import React, { useEffect, useState } from 'react';
import {
  View, SectionList, Text, StyleSheet, RefreshControl
} from 'react-native';
import { colors } from '../../constants/theme';
import { StepItem } from '../../components';
import Http from '../../service/http';
import DataUtil from '../../utils/DataUtil';
import requestCheck from '../../utils/RequestCheckUtil';

export default function Step({ navigation }) {
  const [dataSource, setDataSource] = useState([]);
  const [refresh, setRefresh] = useState(0);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    async function fetchData() {
      setIsLoading(true);
      const res = await Http.getECNList();
      const callback = (d) => setDataSource(DataUtil.convertData2Sections(d));
      requestCheck(res, callback, navigation);
      setIsLoading(false);
    }
    fetchData();
  }, [navigation, refresh]);

  const renderItem = (item) => (<StepItem item={item} navigation={navigation} />);

  const renderSectionHeader = ({ section }) => (
    <View style={[styles.item, styles.section]}>
      <Text style={{ color: 'white' }}>{section.title}</Text>
    </View>
  );

  return (
    <View style={{ flex: 1 }}>
      <SectionList
        sections={dataSource}
        renderItem={(data) => renderItem(data.item)}
        renderSectionHeader={(data) => renderSectionHeader(data)}
        refreshControl={(
          <RefreshControl
            title="加载中"
            titleColor={colors.secondary}
            colors={[colors.primary, colors.secondary]}
            tintColor={colors.primary}
            refreshing={isLoading}
            onRefresh={() => setRefresh(refresh + 1)}
          />
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  section: {
    backgroundColor: colors.tertiary,
    padding: 10,
    marginTop: 1,
    marginBottom: 3,
    alignItems: 'center',
  },
  item: {
    backgroundColor: 'white',
    padding: 10,
    marginHorizontal: 5,
    marginVertical: 3,
    borderColor: colors.gray3,
    borderWidth: 0.5,
    borderRadius: 2,
    shadowColor: colors.gray,
    shadowOffset: { width: 0.5, height: 0.5 },
    shadowOpacity: 0.4,
    shadowRadius: 1,
    elevation: 2
  }
});
